%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int tabstop = 4;
static int indent = 0;
static int addend = 0;
static int nl;
static int ix = 0; /* input position  */
static int ox = 0; /* output position */

static void printspaces(int);
%}

%s COMMENT ONELINECOMM STRINGLITERAL ESCAPED

%%

<INITIAL>^("\n"|"\r\n") { ECHO; } /* spit out empty strings */

<INITIAL>^[ \t\v\r\n]* { /* eat spaces before text */
  ix = yyleng;
 }

<INITIAL>"(" {
  addend += 10;
  REJECT;
 }

<INITIAL>")" {
  addend -= 10;
  REJECT;
 }

<INITIAL>"{"[ \t\v\r\n]* {
  indent++;
  puts("{");
  printspaces(indent * tabstop + addend);
 }

<INITIAL>"}"[ \t\v\r\n]* {
  indent--;
  printspaces(indent * tabstop + addend);
  puts("}");
 }

<INITIAL>"\\" {
  ECHO;
  BEGIN ESCAPED;
 }
<ESCAPED>(.|"\n"|"\r\n") {
  ECHO;
  BEGIN 0;
 }

<INITIAL>"\"" { ECHO; BEGIN STRINGLITERAL; }
<STRINGLITERAL>"\\(.|"\n"|"\r\n")" { ECHO; }
<STRINGLITERAL>"\"" { ECHO; BEGIN 0; }
<STRINGLITERAL>(.|"\n"|"\r\n") { ECHO; }


<INITIAL>(.) {
  if (nl) {
    nl = 0;
    puts("");
  }
  ECHO;
 }

<INITIAL>("\n"|"\r\n") {
  printf("%s", yytext);
  printspaces(4 * indent);
 }

<INITIAL>"/*" { ECHO; BEGIN COMMENT; }
<COMMENT>(.|"\n"|"\r\n") { ECHO; }
<COMMENT>"*/" { ECHO; BEGIN 0; }

<INITIAL>"//" { ECHO; BEGIN ONELINECOMM; }
<ONELINECOMM>"\n"|"\r\n" { ECHO; BEGIN 0; }
<ONELINECOMM>. { ECHO; }

%%

int yywrap(void) { return 1; }

int main(int argc, char **argv) {
	if (argc == 2)
		tabstop = atoi(argv[1]);
	yylex();
	return 0;
}

void printspaces(int n) {
	int i;

	for (i = 0; i < n; i++) {
		putchar(' ');
	}
}
